﻿using UnityEngine;
using YooAsset;

namespace LFrameworkAOT
{
    public class FsmCreateDownloader : IStateNode
    {
        private StateMachine m_Machine;
        PatchOperation m_PatchOperation;

        void IStateNode.OnCreate(StateMachine machine)
        {
            m_Machine = machine;
            m_PatchOperation = m_Machine.Owner as PatchOperation;
        }

        void IStateNode.OnEnter()
        {
            m_PatchOperation.StartCreateDownloader();
            CreateDownloader();
        }
        void IStateNode.OnUpdate()
        {
        }
        void IStateNode.OnExit()
        {
        }

        void CreateDownloader()
        {
            var packageName = (string)m_Machine.GetBlackboardValue("PackageName");
            var package = YooAssets.GetPackage(packageName);
            int downloadingMaxNum = GameLaunch.ParamsSettings.DownloadRoutineCount;
            int failedTryAgain = GameLaunch.ParamsSettings.DownloadRetry;
            var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);
            m_Machine.SetBlackboardValue("Downloader", downloader);

            if (downloader.TotalDownloadCount == 0)
            {
                Debug.Log("Not found any download files !");
                m_PatchOperation.NotDownloadFiles();
            }
            else
            {
                // 发现新更新文件后，挂起流程系统
                // 注意：开发者需要在下载前检测磁盘空间不足
                int totalDownloadCount = downloader.TotalDownloadCount;
                long totalDownloadBytes = downloader.TotalDownloadBytes;
                m_PatchOperation.FoundUpdateFiles(totalDownloadCount, totalDownloadBytes);
            }
        }
    }
}
